<?php
require_once __DIR__ . '/../autoload.php';

use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\json_decode;

$accessKey 		= 'eTaCMQNhH1fNLIhMNL9-iM5qCtIzFmArogDhMe98';
$secretKey 		= 'nA_8Q94IogJPRxWqyZmUAZQJNJj3tCSerZ2Sdbap';
$auth 			= new Auth($accessKey, $secretKey);

//baseUrl构造成私有空间的域名/key的形式
$baseUrl 		= 'oowa7g9hy.bkt.clouddn.com/oqitmeYhKf8_IGSrHbjzVB0FiWWKwvJgFl-mABzJQemwAYKgpebZFgd5not2syx0_1493032740';
$authUrl 		= $auth->privateDownloadUrl($baseUrl);
echo $authUrl;

exit;











$bmgr 			= new BucketManager($auth);
// 获取微信的 access_token
$appid 			= 'wxbb2daf1a23bf7eb1';
$secret 		= 'ddcb3ab6dc75d3e041cfbb80857f4a32';
$url_get 		= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$json			= curlGet($url_get);
$weixin_token 	=  json_decode($json);
$weixin_token	= $weixin_token->access_token;

$img = isset($_POST['media_id'])?$_POST['media_id']:'';
if(empty($img)){
	$res['code'] = '10400';
	$res['msg']  = 'media_id不能为空';
	echo json_encode($res);
	exit;
}else{
	// 从微信服务器下载
	$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$weixin_token."&media_id=".$img;
	$bucket = 'weixin';
	$key = time() . '.jpg';
	list($ret, $err) = $bmgr->fetch($url, $bucket, $key);
	
	//echo "=====> fetch $url to bucket: $bucket  key: $key\n";
	if ($err !== null) {
		$res['code'] = '10400';
		$res['msg']  = '失败';
		echo json_encode($res);
	} else {
		$res['code'] = '10000';
		$res['msg']  = '上传成功';
		echo json_encode($res);
	}
}

function curlGet($url,$data=''){
	$ch = curl_init();
	$header = "Accept-Charset: utf-8";
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	// curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$temp = curl_exec($ch);
	return $temp;
}
